package com.mall.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mall.entity.Category;
import com.mall.entity.SpuInfo;
import com.mall.service.CategoryBrandRelationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mall.common.utils.PageUtils;
import com.mall.common.utils.Query;

import com.mall.dao.BrandDao;
import com.mall.entity.Brand;
import com.mall.service.BrandService;
import org.springframework.util.StringUtils;


@Service("brandService")
public class BrandServiceImpl extends ServiceImpl<BrandDao, Brand> implements BrandService {

    @Autowired
    private BrandDao brandDao;

    @Autowired
    private CategoryBrandRelationService categoryBrandRelationService;

    @Override
    public IPage<Brand> listPage(Integer currentPage, Integer pageSize, String name) {
        List<Brand>list= brandDao.selectByName(name);
        IPage<Brand> page = listToPage(list, currentPage, pageSize);
        return page;
    }

    @Override
    public void updateDetail(Brand brand) {
        //保证冗余字段的一致性
        this.updateById(brand);
        if (!StringUtils.isEmpty(brand.getName())){

            categoryBrandRelationService.updateBrand(brand.getBrandId(),brand.getName());

            //TODO 更新其他的
        }
    }


    /**
     * 转化为ipage的方法
     */
    public static IPage<Brand> listToPage(List<Brand> list, int pageNum, int pageSize){
        List<Brand> pageList = new ArrayList<>();
        int curIdx = pageNum > 1 ? (pageNum - 1) * pageSize : 0;
        for (int i = 0; i < pageSize && curIdx + i < list.size(); i++) {
            pageList.add(list.get(curIdx + i));
        }
        IPage<Brand> page = new Page<>(pageNum, pageSize);
        page.setRecords(pageList);
        page.setTotal(list.size());
        return page;
    }

//    @Override
//    public PageUtils queryPage(Map<String, Object> params) {
//        Page<Category> categoryPage = new Page<>(1, 2);
//
//        IPage<Brand> page = this.page(
//                new Query<Brand>().getPage(params),
//                new QueryWrapper<Brand>()
//        );
//
//        return new PageUtils(page);
//    }

}